//万年历
package test2;
import java.util.InputMismatchException;import java.util.Scanner;
/** 1.输入年份并获取年份* 2.处理异常 输入格式错误异常* 3.输入错误可以继续输入* 4.处理不符合要求的数据* */
public class clander {
    public static void main(String[] args) {
        //获取年份
        int year = getyear();
        System.out.println("日历的年份是: " + year);
        //打印一年的日历
        printcalendar(year);
    }

    private static void printcalendar(int year) {
        for (int month = 1; month <= 12; month++) {
            System.out.println("当前是：" + month + " 月");
            System.out.println("一\t二\t三\t四\t五\t六\t日");
            printmonthofday(year, month);
            System.out.println();
        }
    }    //打印每一天

    private static void printmonthofday(int year, int month) {
        int weekday = getweekday(year, month);
        for (int day = 1; day <= getmonthdays(year, month); day++) {
            if (day == 1) {
                for (int t = 1; t <= getweekday(year, month); t++) {
                    System.out.print("\t");
                }
            }
            System.out.print(day + "\t");
            if ((day + weekday) % 7 == 0) {
                System.out.println();
            }
        }
    }

    private static int getmonthdays(int year, int month) {
        int days = 31;
        if (month == 4 || month == 6 || month == 9 || month == 11) {
            days = 30;
        } else if (month == 2) {
            return isleaf(year) ? 29 : 28;
        }
        return days;
    }

    private static boolean isleaf(int year) {
        if (year % 4 == 0 && year % 100 != 0) {
            return true;
        } else if (year % 400 == 0) {
            return true;
        }
        return false;
    }

    private static int getweekday(int year, int month) {
        int weekday = 0;
        int totals = 0;
        for (int y = 1900; y < year; y++) {
            totals = totals + (isleaf(y) ? 366 : 365);
        }
        for (int m = 1; m < month; m++) {
            totals = totals + getmonthdays(year, m);
        }
        return totals % 7;
    }

    private static int getyear() {
        int year = 1900;
        //计算机的时间从1900年开始。
        boolean flag = true;
        do {
            try {//键入一个年份
                System.out.println("请输入一个年份：比如2020");
                Scanner input = new Scanner(System.in);
                year = input.nextInt();
                //判断是不是一个四位数
                if (year < 1900 || year > 9999) {
                    // 数据不符合要求
                    System.out.println("数据不符合要求");
                    continue;
                }                //如果输入正确就跳出循环
                flag = false;
            } catch (InputMismatchException e) {
                System.out.println("输入的年份格式错误，请再次输入：");
            }
        }
        while (flag);
        return year;
    }
}